<?php
/**
 * 
 * @authors Liujinbi (857053791@QQ.com)
 * @date    2017-10-14 11:33:06
 * @version $Id$
 */

namespace app\mall\controller;
use think\Config;
use think\Db;
use think\Session;
use think\Controller;
use Payinterface\PaySdk;
use think\Log;

class Paynotify {
    
    function __construct(){
        Log::init(Config::get('log_notify'));
      }
    /**
     * out_trade_no
     * sub_openid
     * body
     * total_fee
     * mch_create_ip
     * @return [type] [description]
     */
   //  function index(){
   //      $cfg = Config::get('pay.wx');
   //      $PaySdk = new PaySdk($cfg);

   //      $arr = array(
			// 'out_trade_no'  => '123456789154',
			// 'sub_openid'    => 'oDJYA0b_HkVfzrby_gljXRhKvI6A',
			// 'body'          => '测试',
			// 'total_fee'     => 1,
			// 'mch_create_ip' => '127.0.0.1'
   //      );

   //      $re = $PaySdk->submitOrderInfo($arr);
   //      Log::record('index','error');
   //      Log::record($re,'error');
   //      p($re);
   //  }

   //  function wap(){
   //  	$cfg = Config::get('pay.wap');
   //      $PaySdk = new PaySdk($cfg);

   //      $arr = array(
			// 'out_trade_no'  => '1234567891541',
			// 'body'          => '测试',
			// 'total_fee'     => 1,
			// 'mch_create_ip' => '127.0.0.1',
			// 'device_info' => 'iOS_WAP',
			// 'mch_app_name' => '速冻在线',
			// 'mch_app_id' => 'http://sdzx.tunnel.qydev.com'
   //      );

   //      $re = $PaySdk->submitOrderInfo($arr);
   //      Log::record('wap','error');
   //      Log::record($re,'error');
   //      p($re);
   //  }

    function index(){
    	$xml = file_get_contents('php://input');
    	Log::record('支付回调'.date('Y-m-d H:i:s'),'notify');
        Log::record($xml,'notify');

    	$cfg = Config::get('pay.wap');
        $PaySdk = new PaySdk($cfg);
        $PaySdk->notify([$this,'NotifyCallBack']);
    }

    function NotifyCallBack($data){

    	// 为避免微信支付 商户订单号重复 问题，使用中间表sdzx_order_prepay
        $orderSn = $data['out_trade_no'];
    	//查出订单
    	$order = Db::field('*')->table('sdzx_order')->alias('o')
        ->join('sdzx_order_prepay p','o.order_id=p.order_id')
        ->where("p.out_trade_no='{$orderSn}'")->find();
    	if ($order) {
            if ($order['prepay_type'] == 1) {

                $change_order = Db::name('order_change')->where(['order_id'=>$order['order_id']])->order('change_id desc')->find();
                if ($change_order['pay_status']==1) {
                    return true;
                }else{
                    $updata = [
                        'pay_no'       => $data['transaction_id'],
                        'pay_time'     => date('Y-m-d H:i:s'),
                        'pay_money'    => $data['total_fee']/100, //转换为元
                        'pay_status'   => 1,
                        'pay_platform' => '微信支付'
                    ];

                    if ($order['order_status'] == 25) {
                        $re_change = Db::name('order')->where(['order_id'=>$order['order_id']])->update(['order_status'=>$change_order['bop_order_status']]);
                        if ($re_change===false) {
                            return false;
                        }
                    }

                    $re = Db::name('order_change')->where(['change_id'=>$change_order['change_id']])->update($updata);
                    if ($re!=false) {
                        Db::name('order_prepay')->where(['out_trade_no'=>$orderSn])->update(['status'=>1]);

                        Db::name('order_action')->insert([
                            'user_id'          => $order['user_id'],
                            'order_id'         => $order['order_id'],
                            'act_time'         => date('Y-m-d H:i:s'),
                            'order_status'     => $change_order['bop_order_status'],
                            'bop_order_status' => $order['order_status'],
                            'act_remark'       => '您已支付补价金额，请等待系统确认'
                        ]);

                        // $this->sendTmp($order);
                        return true;
                    }else{
                        return false;
                    }
                }
            }else{
        		if ($order['pay_status'] == 1) { //已经处理
        			return true;
        		}else{
        			$updata = [
    					'pay_no'       => $data['transaction_id'],
    					'pay_time'     => date('Y-m-d H:i:s'),
    					'pay_money'    => $data['total_fee']/100, //转换为元
    					'pay_status'   => 1,
                        'pay_platform' => '威付通'
        			];

                    if ($order['order_status'] == 0) {
                        $updata['order_status'] = 20;
                    }

                    $order['pay_time'] = $updata['pay_time'];
                    $order['pay_money'] = $updata['pay_money'];

        			$re = Db::name('order')->where(['order_id'=>$order['order_id']])->update($updata);
        			if ($re!=false) {
                        $goods = Db::name('order_goods')->where(['order_id'=>$order['order_id']])->select();
                        foreach ($goods as $k => $v) {
                            $r = Db::name('goods_specval')->where(['specval_id'=>$v['goods_specval_id']])->setInc('sales',$v['num']);
                        }

                        Db::name('order_prepay')->where(['out_trade_no'=>$orderSn])->update(['status'=>1]);

                        Db::name('order_action')->insert([
                            'user_id'          => $order['user_id'],
                            'order_id'         => $order['order_id'],
                            'act_time'         => date('Y-m-d H:i:s'),
                            'order_status'     => $updata['order_status'],
                            'bop_order_status' => $order['order_status']
                        ]);
        				return true;
        			}else{
        				return false;
        			}
        		}
            }
    	}else{
    		return false;
    	}
    }
}